package com.jiaolong.controller;

import com.jiaolong.dto.OrderDto;
import com.jiaolong.service.AlipayService;
import com.jiaolong.dto.PaymentRequestDto;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 支付宝支付相关接口
 */
@Slf4j
@Controller // 注意：支付宝返回的是一个支付表单，RestController返回的是统一的json格式数据，Controller既能响应json也能响应html
@RequestMapping("/api/alipay")
public class AlipayController {

    @Autowired
    AlipayService alipayService;

    /**
     * 用户出示付款码支付
     * @param dto 订单参数
     * @param servletResponse
     */
    @PostMapping("/paymentCode")
    public void paymentCode(@RequestBody PaymentRequestDto dto, HttpServletResponse servletResponse) {
        alipayService.paymentCode(dto, servletResponse);
    }

    /**
     * 用户扫码支付
     * @param dto 订单参数
     * @param response
     */
    @PostMapping("/payScanCode")
    public void payScanCode(@RequestBody OrderDto dto, HttpServletResponse response) {
        System.out.println("调用支付宝支付成功");
        alipayService.payScanCode(dto, response);
    }

    /**
     * 支付宝异步回调
     * @param request
     */
    @PostMapping("/alipayNotify")
    public void alipayNotify(HttpServletRequest request) {
        log.info("异步回调执行");
        if(request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            log.info("=====支付宝异步回调成功=====");
            log.info("{}", request);
            alipayService.alipayNotify(request);
        }
    }
}
